#!/bin/bash
# backup_infinity.sh (pigz 加速版)

BACKUP_ROOT="/data/backups/infinity"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_TAR="$BACKUP_ROOT/infinity_backup_$DATE.tar.gz"

VOLUME_DIR="/var/lib/docker/volumes/ragflow_docker_infinity_data/_data"
CONTAINER_NAME="ragflow-infinity"

# === 检查 pigz 是否安装 ===
if ! command -v pigz &> /dev/null; then
    echo "❌ pigz 未安装，建议安装以加速备份"
    echo "💡 Ubuntu/Debian: apt-get install pigz"
    echo "💡 CentOS/Rocky: yum install pigz"
    echo "🔄 正在回退到普通 tar..."
    USE_PIGZ=false
else
    USE_PIGZ=true
fi

# === 创建备份目录 ===
mkdir -p "$BACKUP_ROOT"
if [ $? -ne 0 ]; then
    echo "❌ 无法创建备份目录: $BACKUP_ROOT"
    exit 1
fi

# === 检查数据目录 ===
if [ ! -d "$VOLUME_DIR" ]; then
    echo "❌ 数据目录不存在: $VOLUME_DIR"
    exit 1
fi

# === 停止容器 ===
echo "🛑 停止 Infinity 容器: $CONTAINER_NAME"
docker stop "$CONTAINER_NAME" || { echo "❌ 停止失败"; exit 1; }

# === 开始备份 ===
echo "📦 打包并压缩中..."
echo "📁 目标文件: $BACKUP_TAR"

# 根据是否安装 pigz 选择命令
if [ "$USE_PIGZ" = true ]; then
    # 使用 pigz 并行压缩 + 排除规则
    tar -cf - \
        --exclude='*/tmp' \
        --exclude='*/log/*.log' \
        -C "$VOLUME_DIR" . | pigz > "$BACKUP_TAR"
else
    # 回退到普通 gzip + 排除规则
    tar -czf "$BACKUP_TAR" \
        --exclude='*/tmp' \
        --exclude='*/log/*.log' \
        -C "$VOLUME_DIR" .
fi

if [ $? -ne 0 ]; then
    echo "❌ 备份失败！"
    docker start "$CONTAINER_NAME"
    exit 1
fi

echo "✅ 备份成功: $BACKUP_TAR"
echo "📊 大小: $(du -h "$BACKUP_TAR" | cut -f1)"

# === 重启容器 ===
echo "🚀 启动 Infinity 容器..."
docker start "$CONTAINER_NAME"

# === 清理旧备份 ===
echo "🧹 清理旧备份（保留最新3个）..."
ls -t "$BACKUP_ROOT"/infinity_backup_*.tar.gz 2>/dev/null | tail -n +4 | xargs rm -f

echo "🎉 备份完成"